<?php
// +----------------------------------------------------------------------
// | 幕小铺
// +----------------------------------------------------------------------
// | 版权所有 2016~2020 幕小铺科技（大连）有限公司
// +----------------------------------------------------------------------
// | 2020/03/14
// +----------------------------------------------------------------------

namespace app\video\admin;

use app\admin\controller\Admin;
use app\common\builder\ZBuilder;

use think\facade\Hook;
use think\DB;

/**
 * 视频分类
 * @package app\video\admin
 */
class Classify extends Admin
{
    /**
     * 首页
     * @author shiqiang <976162041@qq.com>
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function index(){
        cookie('__forward__', $_SERVER['REQUEST_URI']);
        
		$list = model('VideoPlayClass') -> getClass();
		// $data = array_column($list, 'title' , 'id');
		foreach($list as $key => $value){
			$video_count = model('VideoPlayClass') -> getVideoPlay() -> where('video_classid', $value['id']) -> count();
			$list[$key]['title_display'] = $value['title_display'] . '('. $video_count .')';
		}
		
		$btn_video = [
			'title' => '查看视频',
			'icon'  => 'fa fa-fw fa-key',
			'class' => 'btn btn-xs btn-default',
			'href'  => url('index/index', ['classid' => '__id__', '_pop' => 1]),
		];
		
		$btn_access = [
			'title' => '添加',
			'icon'  => 'fa fa-fw fa-key',
			'class' => 'btn btn-xs btn-default',
			'href'  => url('add', ['pid' => '__id__']),
		];
		
		$btn_merge = [
			'title' => '合并分类',
			'icon'  => 'fa fa-fw fa-bookmark',
            'class' => 'btn btn-success ajax-post confirm',
			'href'  => url('classMerge'),
		];
		
        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('视频分类') // 设置页面标题
            ->setTableName('video_play_class') // 设置数据表名
            ->addColumns([ // 批量添加列
                ['id', 'id'],
                ['level', '级别'],
				['title_display', '分类标题(视频数量)', 'link', url('index/index', ['classid' => '__id__', '_pop' => 1]), '_blank', 'pop'],
                ['sort', '排序','text.edit'],
                ['right_button', '操作', 'btn']
            ])
            ->addFilter(['report_status']) // 添加筛选
			->addTopButton('add', '', true) // 批量添加顶部按钮
			->addTopButton('custom', $btn_merge) // 批量添加顶部按钮
			->addRightButton('custom', $btn_access) // 添加授权按钮
			->addRightButton('edit', '',true) // 批量添加右侧按钮
			->addRightButton('delete') // 批量添加右侧按钮
			->addRightButton('custom', $btn_video, true) // 查看视频
			->setRowList($list) // 设置表格数据,
            ->fetch(); // 渲染页面
    } 
	
	/**
	 * 合并分类
	 * @author shiqiang <976162041@qq.com>
     * @return mixed
     * @throws \think\Exception
	 */
	public function classMerge(){
		$data = input('post.ids/a');
		
		$video_classid = $data[0];
		unset($data[0]);//合并到第一个分类下
		if(!empty($data)){
			$first_label = model('VideoPlayClassContact') -> where('pid', $video_classid) -> column('label_id');//标签合并
			
			foreach($data as $value){
				$video_list = [];//视频分类修改
				$label_list = [];//标签关联修改
				$label_del = [];//标签关联删除
				
				$rel = model('VideoPlay') -> where('video_classid', $value) -> column('id');
				foreach($rel as $play_id){
					$video_list[] = ['id' => $play_id, 'video_classid' => $video_classid];
				}
				$rel = model('VideoPlay') -> batchEditData($video_list);//修改视频表分类关联
				
				$rel1 = model('VideoPlayClassContact') -> where('pid', $value) -> column('id,label_id');//标签合并
				foreach($rel1 as $key => $label_id){//关联
					if(in_array($label_id, $first_label)){
						$label_del[] = $key;
					}else{
						$label_list[] = ['id' => $key, 'pid' => $video_classid];
					}
				}
				$rel1 = model('VideoPlayClassContact') -> batchEditData($label_list);//修改视频表分类关联
				$rel2 = model('VideoPlayClassContact') -> deleteData($label_del);
				
				if($rel > 0 && $rel1 > 0){
					$rel = model('VideoPlayClass') -> deleteData($value);//删除分类
					if($rel > 0){
						$this->success('合并成功', cookie('__forward__'));
					}else{
						$this->error('修改失败，请重试');
					}
				}else{
					$this->error('修改失败，请重试');
				}
			}
			
		}
		
	}
	
    /**
     * 新增
     * @author shiqiang <976162041@qq.com>
     * @return mixed
     * @throws \think\Exception
     */
    public function add($pid = ''){  
		// 保存数据
		if ($this->request->isPost()) {
			//数据接收
			$data = $this->request->post('', null, 'trim');
			
			$pid        	= isset($data['pid']) ? $data['pid'] : '';
			$title    		= isset($data['title']) ? $data['title'] : '';
			$sort 	 		= isset($data['sort']) ? $data['sort'] : '';
			$label 	 		= isset($data['label']) ? $data['label'] : [];
			$customLabel 	= isset($data['customLabel']) ? $data['customLabel'] : '';
			
			if ($pid == '' || $title == '' || $sort == '') {
                $this->error('数据格式错误');
            }
			DB::startTrans();//启动事务
			//业务逻辑
			$map = [];
			$map['pid'] = $pid;
			$map['title'] = $title;
			$list_class = model('VideoPlayClass') -> where($map) -> find();
			if(!empty($list_class)){
				$this->error('分类标题重复，无法添加');
			}else{
				$rel = model('VideoPlayClass') -> addData($pid, $title, $sort);
				if($rel['code'] == 200){
					if($customLabel != ''){//自定义标签插入
						$customLabel = explode(',', $customLabel);
						$add_label = [];
						$old_label = [];
						foreach($customLabel as $value){//区分原有标签，新标签（新标签插入标签表）
							$label_id = model('VideoPlayClassLabel') -> addDataTage($value);
							$label[] = $label_id['data'];
						}
					}

					$list = [];
					if(!empty($label)){//关联标签
						foreach($label as $value){
							$list[] = ['pid' => $rel['data'], 'label_id' => $value];
						}
						$rel = model('VideoPlayClassContact') -> addData($list);
						if($rel['code'] != 200){
							DB::rollback();
							$this->error($rel['message']);
						}
					}
					
					DB::commit();
					$this->success('新增成功', null, '_parent_reload');
				}else{
					DB::rollback();
					$this->error($rel['message']);
				}
			}
		}
        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('新增分类')
            ->addFormItems([
                ['select', 'pid', '所属上级', '所属上级分类', model('VideoPlayClass') -> getMenuTree(0, ''), $pid],
                ['text', 'title', '分类标题'],
            ])
            ->addText('sort', '排序', '', 100)
			->addTags('customLabel', '自定义标签','多个标签可以用英文 "," 号分割')
			// ->addCheckbox('label', '标签', '', model('VideoPlayClassLabel') -> where('id', 'neq', 1)->column('id,title'))
            ->setTrigger('auto_create', '1', 'child_node', false)
            ->fetch();
    }
	
	/**
     * 编辑
     * @author shiqiang <976162041@qq.com>
     * @return mixed
     * @throws \think\Exception
     */
    public function edit($id = 0, $pid = ''){   
		if ($id === 0) $this->error('缺少参数');
		// 保存数据
		if ($this->request->isPost()) {
			//数据接收
			
			$data = $this->request->post('', null, 'trim');
			$pid        	= isset($data['pid']) ? $data['pid'] : '';
			$title    		= isset($data['title']) ? $data['title'] : '';
			$sort 	 		= isset($data['sort']) ? $data['sort'] : '';
			$label 	 		= isset($data['label']) ? $data['label'] : [];
			$customLabel 	= isset($data['customLabel']) ? $data['customLabel'] : '';
			
			
			if ($pid == '' || $title == '' || $sort == '') {
                $this->error('数据格式错误');
            }
			DB::startTrans();//启动事务
			//业务逻辑
			$map = [
				['id', '<>', $id],
				['pid', '=', $pid],
				['title', '=', $title],
			];
			
			$list_class = model('VideoPlayClass') -> where($map) -> find();
			if(!empty($list_class)){
				$this->error('分类标题重复，无法修改');
			}else{
				$rel = model('VideoPlayClass') -> editData($id ,$pid, $title, $sort);
				
				if($rel['code'] == 200){
					$contact = model('VideoPlayClassContact') -> where('pid', $id) -> column('id,label_id');//源标签
					if(!empty($contact)){//删除原有关联标签
						$unlist = [];
						foreach($contact as $key => $value){
							$unlist[] = $key;
						}
						$rel = model('VideoPlayClassContact') -> deleteData($unlist);
						if($rel['code'] != 200){
							DB::rollback();
							$this->error($rel['message']);
						}
					}
					if($customLabel != ''){//自定义标签插入
						$customLabel = explode(',', $customLabel);
						$add_label = [];
						$old_label = [];
						foreach($customLabel as $value){//区分原有标签，新标签（新标签插入标签表）
							$label_id = model('VideoPlayClassLabel') -> addDataTage($value);
							$label[] = $label_id['data'];
						}
					}
					$list = [];
					if(!empty($label)){//关联标签
						foreach($label as $value){
							$list[] = ['pid' => $id, 'label_id' => $value];
						}
						$rel = model('VideoPlayClassContact') -> addData($list);
						if($rel['code'] != 200){
							DB::rollback();
							$this->error($rel['message']);
						}
					}
					DB::commit();
					$this->success('修改成功', null, '_parent_reload');
				}
			}
		}
		
		$info = model('VideoPlayClass') -> find($id);
		
		$viode_tags = '';	
		$info['label'] = model('VideoPlayClassContact') -> where('pid', $id) -> column('id, label_id');

		$label_info = model('VideoPlayClassLabel') -> where('id', 'in', $info['label']) -> column('title');
		if(is_array($label_info))$viode_tags = implode(',', $label_info);
		
        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('编辑分类')
            ->addFormItems([
                ['select', 'pid', '所属上级', '所属上级分类', model('VideoPlayClass') -> getMenuTree(0, ''), $pid],
                ['text', 'title', '分类标题'],
            ])
            ->addText('sort', '排序')
			->addTags('customLabel', '自定义标签','多个标签可以用英文 "," 号分割', $viode_tags)
			// ->addCheckbox('label', '标签', '', model('VideoPlayClassLabel') -> where('id', 'neq', 1)->column('id,title'))
            ->setTrigger('auto_create', '1', 'child_node', false)
			->setFormData($info)
            ->fetch();
    }
	
	/**
     * 删除
     * @author shiqiang <976162041@qq.com>
     * @return mixed
     * @throws \think\Exception
     */
    public function delete($ids = []){ 
        $class = model('VideoPlayClass') -> where('id', $ids)->find();
		
		// 获取所有后辈id
        $class_childs = model('VideoPlayClass') -> getChildsId($ids);
		// 要删除的所有id
        $all_ids = array_merge([(int)$ids], $class_childs);;
		$rel = model('VideoPlayClass') -> destroy($all_ids);
        if ($rel) {
			$map = [];//删除标签关联
			$map['pid'] = $all_ids;
			$res = model('VideoPlayClassContact') -> destroy(function($query) use ($map){
				$query->where($map);
			});
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }
    }
}
